package com.rong.distributed.transaction.local;

import com.rong.distributed.transaction.mq.MessageDispathcer;
import com.rong.distributed.transaction.mq.bean.Message;
import com.rong.distributed.transaction.mq.constants.TransactionStatus;

/**
 * 
 * 基于两阶段提交的分布事务入口类
 * 
 * @author liurong
 *
 */
public class LocalService {

	private MessageDispathcer messageDispathcer = new MessageDispathcer();

	/**
	 * 执行分布式事务：
	 * 
	 * 1.发送半消息到mq
	 * 
	 * 2.执行本地事务
	 * 
	 * 3.通知mq丢弃或者投递消息
	 */
	public void doService(Integer a, Integer b) {
		// 1.发送半消息
		String messageId = this.sendHalfMessage();

		// 2.执行本地事务，并返回mq状态
		Integer transactiontatus = this.doLocalService(a, b);

		// 3.通知mq
		String mqAckStatus = this.notifyMq(messageId, transactiontatus);

		// 4.根据返回值，判断是否要缓存本地事务到本地。提供给mq回查
		if ("ok".equals(mqAckStatus)) {
			this.saveTransactionStatus(messageId, transactiontatus);
		}
	}

	// 保存本地事务状态
	private void saveTransactionStatus(String messageId, Integer transactiontatus) {

	}

	private String notifyMq(String messageId, Integer transactiontatus) {
		return messageDispathcer.handleHalfMessage(messageId, transactiontatus);
	}

	private Integer doLocalService(Integer a, Integer b) {
		try {
			int res = a / b;
			System.out.println("local:" + res);
			return TransactionStatus.COMMIT.getStatus();
		} catch (Exception e) {
			return TransactionStatus.ROLLBACK.getStatus();
		}
	}

	private String sendHalfMessage() {
		Message message = new Message();
		message.setTopic("tranaction_test");
		message.setContent("分布事务，第三方事务");
		return messageDispathcer.recvHalfMessage(message);
	}
}
